package com.yuan.yblog.search.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



/**
 * @author hepeiyuan on 2024/6/1 19:17
 * @description
 */
@Configuration
public class RabbitmqConfig {
    public static final String QUEUE_ES_MYSQL_CHANGE_SYNC = "queue_es_mysql_synchronization";
    public static final String EXCHANGE_ES_MYSQL_SYNC = "exchange_es_mysql_synchronization";
    public static final String ROUTING_ES_MYSQL_SYNC = "routing_key_es_mysql_synchronization";

    /**
     * 声明队列
     */
    @Bean(QUEUE_ES_MYSQL_CHANGE_SYNC)
    public Queue QUEUE_UPDATE_ES(){
        return new Queue(QUEUE_ES_MYSQL_CHANGE_SYNC);
    }

    /**
     * 声明交换机
     */
    @Bean(EXCHANGE_ES_MYSQL_SYNC)
    public Exchange EXCHANGE_UPDATE_ES(){
        //durable(true) 持久化，mq重启之后交换机还在
        return ExchangeBuilder.directExchange(EXCHANGE_ES_MYSQL_SYNC).durable(true).build();
    }

    /**
     * 绑定队列和交换机
     */
    @Bean
    public Binding BINDING_UPDATE_ES(
            @Qualifier(QUEUE_ES_MYSQL_CHANGE_SYNC) Queue queue,
            @Qualifier(EXCHANGE_ES_MYSQL_SYNC) Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_ES_MYSQL_SYNC).noargs();
    }

    /**
     * JDK序列化方式并不合适。我们希望消息体的体积更小、可读性更高，因此可以使用JSON方式来做序列化和反序列化
     * @return 消息转换器
     */
    @Bean
    public MessageConverter messageConverter() {
        Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
        // 配置自动创建消息id，用于识别不同消息，也可以在业务中基于ID判断是否是重复消息
        jackson2JsonMessageConverter.setCreateMessageIds(true);
        return  jackson2JsonMessageConverter;
    }


}
